package com.huawei.esdk.uc.sametime.toolbar.actions;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.widgets.Display;

import com.huawei.esdk.uc.jna.Constants;
import com.huawei.esdk.uc.sametime.ConstantsDefines;
import com.huawei.esdk.uc.sametime.ConstantsDefines.CallStatus;
import com.huawei.esdk.uc.sametime.international.Messages;
import com.huawei.esdk.uc.sametime.models.Participant;
import com.huawei.esdk.uc.sametime.models.ParticipantList;
import com.huawei.esdk.uc.sametime.services.UCCallService;
import com.huawei.esdk.uc.sametime.util.GlobalConfiguration;
import com.huawei.esdk.uc.sametime.util.PluginUtil;
import com.huawei.esdk.uc.sametime.widgets.EsdkUCConvWindow;
import com.ibm.collaboration.realtime.im.community.CommunityLoginEvent;
import com.ibm.collaboration.realtime.imhub.actions.BuddyListAction;
import com.ibm.collaboration.realtime.livenames.GroupSelection;
import com.ibm.collaboration.realtime.livenames.PersonSelection;
import com.ibm.collaboration.realtime.people.Group;
import com.ibm.collaboration.realtime.people.PeopleUtil;
import com.ibm.collaboration.realtime.people.Person;

/**
 * 主窗口工具栏上的电话会议的控制类 Action contributed to the main window (buddy list).
 * @author y00175154
 */

public class EsdkConfMultiBuddyListAction extends BuddyListAction 
{
    private Logger logger = Logger
            .getLogger(EsdkConfMultiBuddyListAction.class);

    private IStructuredSelection structuredSelection;
    
    private Person[] persons;

    public EsdkConfMultiBuddyListAction()
    {
        super(null);
        logger.debug("EsdkConfMultiBuddyListAction init");
    }

    @Override
    protected void handleCommunityLoginEvent(
            CommunityLoginEvent arg0)
    {
        super.handleCommunityLoginEvent(arg0);
        if(CommunityLoginEvent.TYPE_LOGGED_IN != arg0.getType())
        {
            setEnabled(false);
        }
    }
    
    public void selectionChanged(SelectionChangedEvent event)
    {
        super.selectionChanged(event);

        boolean isUCLogin = GlobalConfiguration.getInstance().isUCLogin();
        boolean isSametimeLogin = GlobalConfiguration.getInstance().isSamtimeLogin();
        boolean isInCall = (CallStatus.end != UCCallService.getCallStatus());
        
        // 只有同时登录了uc和sametime,才能使用工具栏上的功能
        if (isUCLogin && isSametimeLogin && !isInCall && isGroupSelection(event))
        {
            setEnabled(true);
        }
        else
        {
            setEnabled(false);
        }
        firePropertyChange(IAction.ENABLED, null, null);
    }

    private boolean isGroupSelection(SelectionChangedEvent event)
    {
        StructuredSelection select = (StructuredSelection) event.getSelection();
        if (select.size() > 1)
        {
            return true;
        }
        Object[] items = select.toArray();
        for (int i = 0; i < items.length; i++)
        {
            Object item = items[i];
            if (items.length == 1 && item instanceof GroupSelection)
            {
                GroupSelection groupSelection = (GroupSelection) item;
                Group group = groupSelection.getGroup();
                if (null != group.getPersons())
                {
                    return true;
                }
            }
        }
        return false;
    }

    public void run()
    {
        structuredSelection = (IStructuredSelection) getCurrentSelection();
        persons = getSelectedPersons();
        if (null != persons)
        {
            ParticipantList participantList = new ParticipantList();
            for (int i = 0; i < persons.length; i++)
            {
                if (PeopleUtil.isMe(persons[i]))
                {
                    continue;
                }
                Participant participant = new Participant();

                participant.setContactId(persons[i].getContactId());
                String ucAccount = PluginUtil.getUCAccountFromContactID(persons[i]
                        .getContactId());
                participant.setNumber(ucAccount);
                participant.setCallNumType(Constants.AccountType.UC_ACCOUNT);
                participantList.addparticipants(participant);
            }
            // 如果当前没有通话,则可以发起电话会议,否则,给出提示
            if (ConstantsDefines.CallStatus.end == UCCallService
                    .getCallStatus())
            {
                try
                {
                    EsdkUCConvWindow window = EsdkUCConvWindow.getInstance();
                    if(participantList.getparticipants().size()>=2)
                    {
                        window.setConfEnabled(true);
                        Person person = PeopleUtil.getLocalPerson();
                        Participant participant = new Participant();
                        participant.setContactId(person.getContactId());
                        participant.setNumber(PluginUtil.getUCAccountFromContactID(person.getContactId()));
                        participant.setCallNumType(Constants.AccountType.UC_ACCOUNT);
                        participantList.getparticipants().add(0, participant);
                    }
                    window.createUCConvWindow(participantList);
                    window.makeCall(false);
                }
                catch (Exception exception)
                {
                    logger.error(exception.getMessage());
                }
            }
            else
            {
                MessageDialog
                        .openInformation(
                                Display.getCurrent().getActiveShell(),
                                Messages.TIPS,
                                Messages.IS_CALLING);
            }
        }
    }

    @SuppressWarnings("unchecked")
    private Person[] getSelectedPersons()
    {
        if (null == structuredSelection)
        {
            return new Person[0];
        }

        List<Person> items = structuredSelection.toList();
        List<Person> persons = new ArrayList<Person>();
        for (Iterator<Person> it = items.iterator(); it.hasNext();)
        {
            Object item = it.next();
            if (item instanceof PersonSelection)
            {
                PersonSelection personSelection = (PersonSelection) item;
                Person person = personSelection.getPerson();
                persons.add(person);
            }
            if (item instanceof GroupSelection)
            {
                GroupSelection groupSelection = (GroupSelection) item;
                Group group = groupSelection.getGroup();
                Person[] ps = group.getPersons();
                if (ps != null)
                {
                    for (int i = 0; i < ps.length; i++)
                    {
                        persons.add(ps[i]);
                    }
                }
            }
        }
        return persons.toArray(new Person[persons.size()]);
    }

    // private Group[] getSelectedGroups()
    // {
    // if (null == structuredSelection)
    // {
    // return new Group[0];
    // }
    //
    // List items = structuredSelection.toList();
    // List groups = new ArrayList();
    // for (Iterator it = items.iterator(); it.hasNext();)
    // {
    // Object item = it.next();
    // if (item instanceof GroupSelection)
    // {
    // GroupSelection groupSelection = (GroupSelection) item;
    // Group group = groupSelection.getGroup();
    // groups.add(group);
    // }
    // }
    // return (Group[]) groups.toArray(new Group[groups.size()]);
    // }

}
